package com.jindu.producer.finance.controller;


import com.jindu.kernel.page.AlphaPage;
import com.jindu.kernel.result.JsonResult;
import com.jindu.kernel.utils.AlphaBeanUtils;
import com.jindu.kernel.utils.DateUtils;
import com.jindu.kernel.utils.IdGenerator;
import com.jindu.producer.finance.jpa.ContentJpa;
import com.jindu.producer.finance.model.CContentEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jarvis
 * @date 2018/1/28
 */
@Api(description = "新闻资讯管理", tags = "ContentController", basePath = "/content")
@RestController
@RequestMapping(value = "/content",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ContentController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ContentJpa contentJpa;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据资讯ID，查询资讯或新闻的信息", notes = "返回单个资讯的信息")
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public JsonResult<CContentEntity> get(@RequestParam String id){
        return JsonResult.getSuccessResult(contentJpa.findById(id));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据分页参数，查询资讯或新闻的信息", notes = "返回资讯的信息集合")
    @RequestMapping(value = "getAll",method = RequestMethod.GET)
    public JsonResult<AlphaPage<CContentEntity>> getAll(@RequestParam(value = "pageNo",defaultValue = "0") Integer pageNo,
                                                        @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                                        @RequestParam(value = "lang",required = false) Integer lang,
                                                        @RequestParam(value = "title", required = false) String title){

        Specification querySpecifi = (Specification<CContentEntity>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if(title != null){
                predicates.add(criteriaBuilder.like(root.get("title"),"%"+title+"%"));
            }
            if(lang != null){
                predicates.add(criteriaBuilder.equal(root.get("lang"),lang));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Page<CContentEntity> entities=contentJpa.findAll(querySpecifi,new PageRequest(pageNo, pageSize,sort));
        return new AlphaPage<>(entities).toJsonResult();
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "保存资讯信息", notes = "保存资讯的信息")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public JsonResult<CContentEntity> save(@RequestBody CContentEntity contentEntity){

        CContentEntity cContentEntity=contentJpa.findById(contentEntity.getId());

        if(cContentEntity == null){
            contentEntity.setId(IdGenerator.uuid());
            contentEntity.setCreateTime(new Timestamp(DateUtils.getCurrentTime()));
            contentEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
            return JsonResult.getSuccessResult(contentJpa.saveAndFlush(contentEntity));
        }else {
            contentEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
            BeanUtils.copyProperties(contentEntity,cContentEntity,AlphaBeanUtils.getNullPropertyNames(contentEntity));
            return JsonResult.getSuccessResult(contentJpa.saveAndFlush(cContentEntity));
        }
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "删除资讯内容的信息", notes = "根据资讯的ID,删除数据")
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public JsonResult<Integer> delete(@RequestBody String id){
        return JsonResult.getSuccessResult(contentJpa.deleteById(id));
    }

}
